<template>
  <div class="server-list p-4">
    <el-card class="box-card">
      <template #header>
        <div class="card-header flex items-center justify-between">
          <h2 class="text-xl font-bold">服务器列表</h2>
          <el-button type="primary" @click="goToCreate">添加服务器</el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-container mb-4 flex flex-wrap items-center gap-4">
        <el-input
          v-model="queryParams.ip"
          placeholder="IP地址"
          class="w-48"
          clearable
          @clear="handleQuery"
        />
        <el-input
          v-model="queryParams.hostname"
          placeholder="主机名"
          class="w-48"
          clearable
          @clear="handleQuery"
        />
        <el-input
          v-model="queryParams.sn"
          placeholder="序列号"
          class="w-48"
          clearable
          @clear="handleQuery"
        />
        
        <el-select v-model="queryParams.server_type" placeholder="服务器类型" clearable @change="handleQuery" class="w-32">
          <el-option label="Web服务器" :value="ServerType.WEB" />
          <el-option label="数据库服务器" :value="ServerType.DATABASE" />
          <el-option label="应用服务器" :value="ServerType.APPLICATION" />
          <el-option label="文件服务器" :value="ServerType.FILE" />
          <el-option label="缓存服务器" :value="ServerType.CACHE" />
          <el-option label="代理服务器" :value="ServerType.PROXY" />
          <el-option label="其他" :value="ServerType.OTHER" />
        </el-select>
        
        <el-select v-model="queryParams.server_status" placeholder="服务器状态" clearable @change="handleQuery" class="w-32">
          <el-option label="在线" :value="ServerStatus.ONLINE" />
          <el-option label="离线" :value="ServerStatus.OFFLINE" />
          <el-option label="维护中" :value="ServerStatus.MAINTENANCE" />
          <el-option label="已退役" :value="ServerStatus.DECOMMISSIONED" />
        </el-select>
        
        <el-select v-model="queryParams.usage_status" placeholder="使用状态" clearable @change="handleQuery" class="w-32">
          <el-option label="使用中" :value="ServerUsageStatus.IN_USE" />
          <el-option label="可用" :value="ServerUsageStatus.AVAILABLE" />
          <el-option label="已预留" :value="ServerUsageStatus.RESERVED" />
          <el-option label="已报废" :value="ServerUsageStatus.RETIRED" />
        </el-select>

        <el-select v-model="queryParams.environment" placeholder="服务器环境" clearable @change="handleQuery" class="w-32">
          <el-option label="测试环境" :value="ServerEnvironment.TESTING" />
          <el-option label="开发环境" :value="ServerEnvironment.DEVELOPMENT" />
          <el-option label="线上环境" :value="ServerEnvironment.PRODUCTION" />
        </el-select>
        
        <el-button type="primary" @click="handleQuery">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </div>

      <!-- 表格区域 -->
      <el-table
        v-loading="loading"
        :data="serverList"
        stripe
        border
        style="width: 100%"
      >
        <el-table-column prop="ip" label="IP地址" width="140" />
        <el-table-column prop="hostname" label="主机名" width="160" show-overflow-tooltip />
        <el-table-column prop="product_line" label="产品线" width="120" show-overflow-tooltip />
        <el-table-column label="服务器类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getServerTypeTag(row.server_type)">
              {{ getServerTypeName(row.server_type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="服务器状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.server_status)">
              {{ getStatusName(row.server_status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="使用状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getUsageStatusTag(row.usage_status)">
              {{ getUsageStatusName(row.usage_status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="环境" width="100">
          <template #default="{ row }">
            <el-tag :type="getEnvironmentTag(row.environment)" v-if="row.environment">
              {{ getEnvironmentName(row.environment) }}
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="rack_location" label="机柜位置" width="120" show-overflow-tooltip />
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="goToDetail(row.id)">详情</el-button>
            <el-button type="primary" link @click="goToEdit(row.id)">编辑</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-container mt-4 flex justify-end">
        <el-pagination
          v-model:current-page="queryParams.page"
          v-model:page-size="queryParams.page_size"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts" name="ServerList">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

import { getServerList, deleteServer } from '@/request/server-api'
import { Server, ServerType, ServerStatus, ServerUsageStatus, ServerEnvironment } from '@/model/server-model'

// 分页数据接口定义
interface PagedData<T> {
  items: T[]
  total: number
  page: number
  page_size: number
}

// 旧格式分页数据接口定义
interface LegacyPagedData<T> {
  list: T[]
  total?: number
}

// 路由对象
const router = useRouter()

// 服务器列表
const serverList = ref<Server[]>([])

// 加载状态
const loading = ref(false)

// 总条数
const total = ref(0)

// 查询参数
const queryParams = reactive({
  page: 1,
  page_size: 20,
  ip: '',
  hostname: '',
  sn: '',
  server_type: '',
  server_status: '',
  usage_status: '',
  environment: ''
})

/**
 * 获取服务器列表
 */
const getList = async () => {
  loading.value = true
  try {
    // 构建查询参数
    const params = {
      page: queryParams.page,
      page_size: queryParams.page_size,
      ...(queryParams.ip ? { ip: queryParams.ip } : {}),
      ...(queryParams.hostname ? { hostname: queryParams.hostname } : {}),
      ...(queryParams.sn ? { sn: queryParams.sn } : {}),
      ...(queryParams.server_type ? { server_type: queryParams.server_type } : {}),
      ...(queryParams.server_status ? { server_status: queryParams.server_status } : {}),
      ...(queryParams.usage_status ? { usage_status: queryParams.usage_status } : {}),
      ...(queryParams.environment ? { environment: queryParams.environment } : {})
    }

    const response = await getServerList(params)
    if (response.code === 0) {
      // 判断返回的数据结构，适配不同的返回格式
      if (response.data && typeof response.data === 'object' && 'items' in response.data && Array.isArray(response.data.items)) {
        // 新API格式：data包含items数组和total
        const pagedData = response.data as unknown as PagedData<Server>
        serverList.value = pagedData.items
        total.value = pagedData.total || 0
      } else if (response.data && typeof response.data === 'object' && 'list' in response.data && Array.isArray(response.data.list)) {
        // 兼容旧格式：data 包含list数组
        const legacyData = response.data as unknown as LegacyPagedData<Server>
        serverList.value = legacyData.list
        total.value = legacyData.total || response.total || 0
      } else {
        // 直接数组的情况
        serverList.value = response.data as Server[]
        total.value = response.total || 0
      }
    } else {
      ElMessage.error(response.errorMsg || '获取服务器列表失败')
    }
  } catch (error) {
    console.error('获取服务器列表失败:', error)
    ElMessage.error('获取服务器列表失败')
  } finally {
    loading.value = false
  }
}

/**
 * 处理查询
 */
const handleQuery = () => {
  queryParams.page = 1
  getList()
}

/**
 * 重置查询
 */
const resetQuery = () => {
  queryParams.page = 1
  queryParams.page_size = 20
  queryParams.ip = ''
  queryParams.hostname = ''
  queryParams.sn = ''
  queryParams.server_type = ''
  queryParams.server_status = ''
  queryParams.usage_status = ''
  queryParams.environment = ''
  handleQuery()
}

/**
 * 处理分页大小变化
 */
const handleSizeChange = (val: number) => {
  queryParams.page_size = val
  getList()
}

/**
 * 处理页码变化
 */
const handleCurrentChange = (val: number) => {
  queryParams.page = val
  getList()
}

/**
 * 获取服务器类型标签类型
 */
const getServerTypeTag = (type: ServerType): 'primary' | 'success' | 'warning' | 'info' | 'danger' => {
  switch (type) {
    case ServerType.WEB:
      return 'primary'
    case ServerType.DATABASE:
      return 'success'
    case ServerType.APPLICATION:
      return 'warning'
    case ServerType.FILE:
      return 'info'
    case ServerType.CACHE:
      return 'success'
    case ServerType.PROXY:
      return 'primary'
    default:
      return 'info'
  }
}

/**
 * 获取服务器类型名称
 */
const getServerTypeName = (type: ServerType): string => {
  switch (type) {
    case ServerType.WEB:
      return 'Web服务器'
    case ServerType.DATABASE:
      return '数据库服务器'
    case ServerType.APPLICATION:
      return '应用服务器'
    case ServerType.FILE:
      return '文件服务器'
    case ServerType.CACHE:
      return '缓存服务器'
    case ServerType.PROXY:
      return '代理服务器'
    case ServerType.OTHER:
      return '其他'
    default:
      return type
  }
}

/**
 * 获取状态标签类型
 */
const getStatusTag = (status: ServerStatus): 'primary' | 'success' | 'warning' | 'info' | 'danger' => {
  switch (status) {
    case ServerStatus.ONLINE:
      return 'success'
    case ServerStatus.OFFLINE:
      return 'danger'
    case ServerStatus.MAINTENANCE:
      return 'warning'
    case ServerStatus.DECOMMISSIONED:
      return 'info'
    default:
      return 'info'
  }
}

/**
 * 获取状态名称
 */
const getStatusName = (status: ServerStatus): string => {
  switch (status) {
    case ServerStatus.ONLINE:
      return '在线'
    case ServerStatus.OFFLINE:
      return '离线'
    case ServerStatus.MAINTENANCE:
      return '维护中'
    case ServerStatus.DECOMMISSIONED:
      return '已退役'
    default:
      return status
  }
}

/**
 * 获取使用状态标签类型
 */
const getUsageStatusTag = (status: ServerUsageStatus): 'primary' | 'success' | 'warning' | 'info' | 'danger' => {
  switch (status) {
    case ServerUsageStatus.IN_USE:
      return 'primary'
    case ServerUsageStatus.AVAILABLE:
      return 'success'
    case ServerUsageStatus.RESERVED:
      return 'warning'
    case ServerUsageStatus.RETIRED:
      return 'info'
    default:
      return 'info'
  }
}

/**
 * 获取使用状态名称
 */
const getUsageStatusName = (status: ServerUsageStatus): string => {
  switch (status) {
    case ServerUsageStatus.IN_USE:
      return '使用中'
    case ServerUsageStatus.AVAILABLE:
      return '可用'
    case ServerUsageStatus.RESERVED:
      return '已预留'
    case ServerUsageStatus.RETIRED:
      return '已报废'
    default:
      return status
  }
}

/**
 * 获取环境标签类型
 */
const getEnvironmentTag = (environment?: ServerEnvironment): 'primary' | 'success' | 'warning' | 'info' | 'danger' => {
  if (!environment) return 'info'
  switch (environment) {
    case ServerEnvironment.TESTING:
      return 'info'
    case ServerEnvironment.DEVELOPMENT:
      return 'warning'
    case ServerEnvironment.PRODUCTION:
      return 'success'
    default:
      return 'info'
  }
}

/**
 * 获取环境名称
 */
const getEnvironmentName = (environment?: ServerEnvironment): string => {
  if (!environment) return '-'
  switch (environment) {
    case ServerEnvironment.TESTING:
      return '测试环境'
    case ServerEnvironment.DEVELOPMENT:
      return '开发环境'
    case ServerEnvironment.PRODUCTION:
      return '线上环境'
    default:
      return environment
  }
}

/**
 * 跳转到创建页面
 */
const goToCreate = () => {
  router.push('/server/create')
}

/**
 * 跳转到详情页面
 */
const goToDetail = (id: number) => {
  router.push(`/server/detail/${id}`)
}

/**
 * 跳转到编辑页面
 */
const goToEdit = (id: number) => {
  router.push(`/server/edit/${id}`)
}

/**
 * 处理删除
 */
const handleDelete = (row: Server) => {
  ElMessageBox.confirm(`确认删除服务器 "${row.hostname}" (${row.ip}) 吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      try {
        const response = await deleteServer(Number(row.id))
        if (response.code === 0) {
          ElMessage.success('删除成功')
          getList()
        } else {
          ElMessage.error(response.errorMsg || '删除失败')
        }
      } catch (error) {
        console.error('删除服务器失败:', error)
        ElMessage.error('删除服务器失败')
      }
    })
    .catch(() => {
      // 取消删除操作
    })
}

onMounted(() => {
  getList()
})
</script>

<style scoped lang="scss">
.server-list {
  .pagination-container {
    padding: 10px 0;
  }
  
  .el-button.el-button--primary.is-link,
  .el-button.el-button--danger.is-link {
    padding: 0 6px;
    margin-right: 0;
  }
}
</style>
